#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "user.hpp"

class UdpServer
{
public:
    UdpServer(uint16_t port, const std::string &ip = "")
        : _ip(ip), _port(port), _sockfd(-1)
    {
    }

    ~UdpServer()
    {
    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            // 创建套接字失败
            std::cerr << "create socket error, errno: " << errno << " strerrno : " << strerror(errno) << std::endl;
            exit(1);
        }

        // bind,绑定ip和端口号
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        int n = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            // bind失败
            std::cerr << "bind ip and port error, errno: " << errno << " strerrno : " << strerror(errno) << std::endl;
            exit(2);
        }
    }

    // 启动服务器
    void Start()
    {
        char buffer[1024];
        std::string str;
        struct sockaddr_in addr;
        socklen_t addrlen = sizeof(addr);

        while (true)
        {
            // 接受信息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &addrlen);
            std::string ip = inet_ntoa(addr.sin_addr);
            uint16_t port = ntohs(addr.sin_port);
            buffer[n] = 0;

            char name[1024];
            snprintf(name, sizeof(name), "[ip: %s   port: %d]", ip.c_str(), port);

            std::string mes;

            // 如果该ip和端口号第一次发消息，则保存起来
            if (strcmp(buffer, "online") == 0)
            {
                std::cout << "online success " << std::endl;
                _us.AddUser(name, User(ip, port, addr));

                mes = "上线成功!\n";
                sendto(_sockfd, mes.c_str(), mes.size(), 0, (struct sockaddr *)&addr, sizeof addr);

                for (auto us : _us.users)
                {
                    std::cout << us.first << std::endl;
                }
            }
            else if (strcmp(buffer, "offline") == 0)
            {
                _us.DelUser(name);
                mes = "下线成功!\n";
                sendto(_sockfd, mes.c_str(), mes.size(), 0, (struct sockaddr *)&addr, sizeof addr);
            }
            else
            {
                mes += name;
                mes += "  say:  ";
                mes += buffer;\
                mes += '\n';

                // 将这条消息发给每一个人
                for (auto &user : _us.users)
                {
                    sendto(_sockfd, mes.c_str(), mes.size(), 0, (struct sockaddr *)&(user.second._addr), sizeof user.second._addr);
                }
            }
        }
    }

private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
    OnlineUsers _us;
};